package com.tanhua.dubbo.server.api;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.config.HuanXinConfig;
import com.tanhua.dubbo.server.enums.HuanXinMessageType;
import com.tanhua.dubbo.server.mapper.HuanXinUserMapper;
import com.tanhua.dubbo.server.pojo.HuanXinUser;
import com.tanhua.dubbo.server.service.RequestService;
import com.tanhua.dubbo.server.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName: HuanXinApiImpl
 * @Author:王晨晗
 * @Description: 环信平台操作接口实现类
 * @Date: 2022/01/05/16:52
 */
@Service
@Slf4j
public class HuanXinApiImpl implements HuanXinApi{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private RequestService requestService;

    @Autowired
    private HuanXinConfig huanXinConfig;

    @Autowired
    private HuanXinUserMapper huanXinUserMapper;


    /**
     * @description 获取环信平台的token
     * @return
     */
    @Override
    public String getToken() {
        //调用tokenService的获取token方法进行获取token
        return tokenService.getToken();
    }

    /**
     * @description 在环信平台注册用户
     * @param userId
     * @return
     */
    @Override
    public Boolean register(Long userId) {
        //请求路径
        String targetUrl = huanXinConfig.getUrl() + huanXinConfig.getOrgName() + "/" + huanXinConfig.getAppName() + "/users";
        //注册用户的信息
        HuanXinUser huanXinUser = new HuanXinUser();
        huanXinUser.setUsername("HX_" + userId);        //用户名
        huanXinUser.setPassword(IdUtil.simpleUUID());       //随机生成密码

        //发送注册请求
        HttpResponse response = requestService.execute(targetUrl, JSONUtil.toJsonStr(Arrays.asList(huanXinUser)), Method.POST);

        //判断注册状态
        if (response.isOk()){
            //将用户信息写入到数据库中
            huanXinUser.setUserId(userId);
            huanXinUser.setCreated(new Date());
            huanXinUser.setCreated(huanXinUser.getCreated());

            huanXinUserMapper.insert(huanXinUser);

            return true;
        }
        return false;
    }

    /**
     * @description 查询环信用户信息
     * @param userId
     * @return
     */
    @Override
    public HuanXinUser queryHuanXinUser(Long userId) {
        QueryWrapper<HuanXinUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id" , userId);
        return huanXinUserMapper.selectOne(wrapper);
    }

    /**
     * @description 根据环信用户名查询环信信息
     * @param userName
     * @return
     */
    @Override
    public HuanXinUser queryUserByUserName(String userName) {
        QueryWrapper<HuanXinUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username" , userName);
        return huanXinUserMapper.selectOne(wrapper);
    }

    /**
     * @description 保存好友信息
     * @param userId
     * @param friendId
     * @return
     */
    @Override
    public Boolean addUserFriend(Long userId, Long friendId) {
        //生成任务url路径
        String targetUrl = huanXinConfig.getUrl() + huanXinConfig.getOrgName() + "/" + huanXinConfig.getAppName() + "/users/HX_" + userId + "/contacts/users/HX_" + friendId;
        try {
            return requestService.execute(targetUrl , null , Method.POST).isOk();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //添加失败
        return false ;
    }

    /**
     * @description 删除好友关系
     * @param userId
     * @param friendId
     * @return
     */
    @Override
    public Boolean removeUserFriend(Long userId, Long friendId) {
        String targetUrl = huanXinConfig.getUrl() + huanXinConfig.getOrgName() + "/" + huanXinConfig.getAppName() + "/users/HX_" + userId + "/contacts/users/HX_" + friendId;
        try {
            return requestService.execute(targetUrl , null , Method.DELETE).isOk();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //删除失败
        return false ;
    }

    /**
     * @description 以管理员身份发送默聊消息回复
     * @param targetUserName
     * @param huanXinMessageType
     * @param msg
     * @return
     */
    @Override
    public Boolean sendMsgFromAdmin(String targetUserName, HuanXinMessageType huanXinMessageType, String msg) {
        //请求url路径
        String targetUrl = huanXinConfig.getUrl() + huanXinConfig.getOrgName() + "/" + huanXinConfig.getAppName() + "/messages";
        try {
            //生成请求体内容
            String body = JSONUtil.createObj()
                    .set("target_type" , "users")
                    .set("target" , JSONUtil.createArray().set(targetUserName))
                    .set("msg" , JSONUtil.createObj()
                            .set("type" , huanXinMessageType.getType())
                            .set("msg",msg)).toString();
            //执行发送
            return requestService.execute(targetUrl , body , Method.POST).isOk();
        } catch (JSONException e) {
            log.error("发送消息失败~ targetUserName = " + targetUserName+", type = " + huanXinMessageType.getType()+", msg = " + msg, e);
        }
        return false;
    }

    /**
     * @description 添加黑名单
     * @param id
     * @param userId
     * @return
     */
    @Override
    public Boolean addBlackUser(Long id, Long userId) {
        //生成任务url路径
        String targetUrl = huanXinConfig.getUrl() + huanXinConfig.getOrgName() + "/" + huanXinConfig.getAppName() + "/users/HX_" + id + "/blocks/users";
        try {
            //生成请求体
            String body = JSONUtil.createObj().set("usernames" , JSONUtil.createArray().set("HX_" + userId)).toString();
            //发送请求,获取请求结果并返回
            return requestService.execute(targetUrl , body , Method.POST).isOk();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //添加黑名单失败
        return false ;
    }

    /**
     * @description 移除黑名单
     * @param id
     * @param userId
     * @return
     */
    @Override
    public Boolean removeBlackUser(Long id, Long userId) {
        //生成任务url路径
        String targetUrl = huanXinConfig.getUrl() + huanXinConfig.getOrgName() + "/" + huanXinConfig.getAppName() + "/users/HX_" + id + "/blocks/users/HX_" + userId;
        try {
            //发送请求,获取请求结果并返回
            return requestService.execute(targetUrl , null , Method.DELETE).isOk();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //删除黑名单失败
        return false ;
    }
}
